exports.bulk_purchase_activity_solitaier_join = function (req, res) {

    var bodyParams = req.routeInfo.bodyParams;

    //最终结果
    var resultData = {};

    var userInfo = {};

    var oa_title = "";

    var oa_oid = 0;

    var joinCount = 0;

    var nowStageCode = 0;

    var nowStageCount = 0;

    var nowStagePrice = 0;

    var beforeStageCode = 0;

    var beforeStageCount = 0;

    var beforeStagePrice = 0;

    var shouldRefundOrderInfo = 0;

    var userMaxCount = 0;

    var oa_end_time = 0;

    var oa_start_time = 0;


    //任务流创建
    async.waterfall([

            //参加活动
            function (cb) {

                R.SEND_HTTP(
                    req,
                    {
                        url: CORE_APIConfig.coreAPI.bulkPurchaseActivitySolitaierJoin,
                        method: 'POST',
                        data: {
                            "u_id": bodyParams.u_id,
                            "oa_id": bodyParams.oa_id,
                            "order_NO": bodyParams.order_NO,
                            "is_validation": bodyParams.is_validation
                        }
                    },
                    function (err, data) {
                        console.log(111,data);

                        //判断是否有错误信息
                        if (err) {
                            return RES.response(res, true, data);
                        }

                        //判断是否为验证操作
                        if (bodyParams.is_validation == 1) {

                            return RES.response(res, true, data);

                        } else {

                            cb();

                        }

                    }
                );
            },

            //查询活动名称
            function (cb) {

                R.SEND_HTTP(
                    req,
                    {
                        url: CORE_APIConfig.coreAPI.search_organization_activity_info + "/oa_id/" + bodyParams.oa_id,
                        method: 'POST',
                        data: {
                            fields: ["oa_title","oa_oid","oa_join_count","oa_end_time","oa_start_time"].join(",")
                        }
                    },
                    function (err, data) {
                        console.log(222,data);
                        //判断是否有错误信息
                        if (err) {
                            return cb(err, data);
                        }

                        oa_title = data.data[0].oa_title;

                        oa_oid   = data.data[0].oa_oid;

                        oa_end_time = data.data[0].oa_end_time;

                        oa_start_time = data.data[0].oa_start_time;

                        joinCount = data.data[0].oa_join_count;

                        cb();

                    }
                );

            },


            // //查询活动配置信息（是否有优惠劵奖励）
            // function(cb){
            //
            //
            //     R.SEND_HTTP(
            //         req,
            //         {
            //             url: CORE_APIConfig.coreAPI.searchBulkPurchaseActivityConfig + "/bpac_oaid/"+bodyParams.oa_id,
            //             method: 'POST',
            //             data:{
            //                 fields : ["bpac_participant_coupon_id","bpac_participant_coupon_type"].join(",")
            //             }
            //         },
            //         function (err, data) {
            //
            //             console.log(333,data);
            //
            //             //判断是否有错误信息
            //             if (err) {
            //                 return cb();
            //             }
            //
            //             var coupon = data.data[0];
            //
            //             //判断是否有开团奖励代金劵
            //             if(coupon.bpac_participant_coupon_id == 0){
            //                 return cb();
            //             }
            //
            //
            //             //如果有代金劵将代金劵写入用户代金劵表
            //             if(coupon.bpac_participant_coupon_type == 0){  //代金劵
            //
            //                 R.SEND_HTTP(
            //                     req,
            //                     {
            //                         url    : CORE_APIConfig.coreAPI.addUserCashCoupon,
            //                         method : 'POST',
            //                         data:{
            //                             ucc_uid : bodyParams.u_id,
            //                             ucc_ccid : coupon.bpac_participant_coupon_id
            //                         }
            //                     },
            //                     function (err, data) {
            //
            //                         cb();
            //
            //                     }
            //                 );
            //
            //             }else if(coupon.bpac_participant_coupon_type == 1){ //约课劵
            //
            //                 R.SEND_HTTP(
            //                     req,
            //                     {
            //                         url    : CORE_APIConfig.coreAPI.add_course_coupon,
            //                         method : 'POST',
            //                         data:{
            //                             ucc_uid : bodyParams.u_id,
            //                             ucc_ccid : coupon.bpac_participant_coupon_id
            //                         }
            //                     },
            //                     function (err, data) {
            //
            //                         cb();
            //
            //                     }
            //                 );
            //
            //
            //             }else if(coupon.bpac_participant_coupon_type == 2){ //兑换卷
            //
            //                 R.SEND_HTTP(
            //                     req,
            //                     {
            //                         url    : CORE_APIConfig.coreAPI.add_exchange_coupon,
            //                         method : 'POST',
            //                         data:{
            //                             uec_uid : bodyParams.u_id,
            //                             uec_ecid : coupon.bpac_participant_coupon_id
            //                         }
            //                     },
            //                     function (err, data) {
            //
            //                         cb();
            //
            //                     }
            //                 );
            //
            //             }else {
            //                 return cb();
            //             }
            //
            //         }
            //     );
            //
            // },


        //生成消费码
        function(cb){

            R.SEND_HTTP(
                req,
                {
                    url: CORE_APIConfig.coreAPI.addConsumeNum,
                    method: 'POST',
                    data  : {
                        cn_uid  : bodyParams.u_id,
                        cn_oid  : oa_oid,
                        cn_coid : 0,
                        cn_ono  : bodyParams.order_NO
                    }
                },
                function (err, data) {
                    console.log(444,data);
                    //判断是否有错误信息
                    if (err) {
                        //console.log("消费码生成失败");
                    }
                    //console.log("消费码生成成功");
                    cb();

                }
            );

        },

        //查询接龙档位及价格
        function (cb) {

            R.SEND_HTTP(
                req,
                {
                    url: CORE_APIConfig.coreAPI.search_bulk_purchase_activity_config + "/bpac_oaid/" + bodyParams.oa_id,
                    method: 'POST',
                    data: {
                        fields: ["bpac_min_count", "bpac_participation_price","bpac_max_user_count"].join(",")
                    }
                },
                function (err, data) {
                    console.log(555,data);
                    //判断是否有错误信息
                    if (err) {
                        return cb(err, data);
                    }

                    var memberConfig = data.data;

                    userMaxCount = memberConfig[0].bpac_max_user_count;

                    var stageData = memberConfig[0].bpac_min_count.split("|");  //对各阶段对应参团人数分割

                    var stagePriceData = memberConfig[0].bpac_participation_price.split("|");//对各阶段对应参团价格分割

                    for (var i = 0; i < stageData.length; i++) {

                        var stageCount = stageData[i].split("-");

                        if (parseInt(stageCount[0]) <= parseInt(joinCount) && parseInt(joinCount) <= parseInt(stageCount[1])) {

                            nowStageCode = i;                   //当前用户参团的阶段
                            nowStageCount = stageCount[1];      //当前用户参团阶段的最大参团人数
                            nowStagePrice = stagePriceData[i];  //当前用户参团阶段对应的价格

                        }

                    }

                    for (var a = 0; a < stageData.length; a++) {

                        var stageCount2 = stageData[a].split("-");

                        if (parseInt(stageCount2[0]) <= parseInt(joinCount) - 1 && parseInt(joinCount) - 1 <= parseInt(stageCount2[1])) {

                            beforeStageCode = a;                    //当前用户参团前的阶段
                            beforeStageCount = stageCount2[1];      //当前用户参团前的阶段的最大参团人数
                            beforeStagePrice = stagePriceData[a];   //当前用户参团前的阶段对应的价格

                        }

                    }
                    cb();

                }
            );

        },
        //退款订单查询
        function (cb) {

            ///limit/" + beforeStageCount
            if (parseInt(nowStageCode) > parseInt(beforeStageCode)) {
                R.SEND_HTTP(
                    req,
                    {
                        url: CORE_APIConfig.coreAPI.search_order + "/o_aoc_id/" + bodyParams.oa_id + "/o_pay_status/1/sort_order/o_id-asc",
                        method: 'POST',
                        data: {
                            fields: ["o_id", "o_uid", "o_we_chat_no", "o_balance_pay", "o_wechat_pay","o_money","o_phone","o_no"].join(",")
                        }
                    },
                    function (err, data) {

                        console.log(555,data);

                        //判断是否有错误信息
                        if (err) {
                            return cb(err, data);
                        }

                        shouldRefundOrderInfo = data.data;

                        cb();
                    }
                );
            } else {
                shouldRefundOrderInfo = [];
                cb();
            }
        },
        //退款
        function (cb) {

            //创建添加任务
            var tasks = [];

            if (shouldRefundOrderInfo.length <= 0) {
    
                resultData.shoudNotRefundReason = "没有需要退款的订单";

                cb();

            } else {


                //循环节点列表
                shouldRefundOrderInfo.forEach(function (item, i) {

                   

                    //创建每一个插入任务
                    tasks.push(function (callback) {

                        //console.log("准备退款的对象：" + item.o_we_chat_no);


                        var refundValue = item.o_money *100 - nowStagePrice * 100;

                        if(refundValue == 0){
                            return callback();
                        }

                        //调用微信退款
                        R.SEND_HTTP(
                            req,
                            {
                                url: "http://localhost:3400/weixin/reimburse",
                                method: 'POST',
                                data: {
                                    action: "tuikuan",
                                    transaction_id: item.o_we_chat_no,
                                    total_fee: item.o_wechat_pay * 100,
                                    refund_fee: refundValue
                                }

                            },
                            function (err, data) {

                                console.log("微信退款处理....." + data);


                                //console.log("准备接收退款的手机号码....." + item.o_phone);

                                //发送短信
                                if( item.o_phone == "" ){
                                    return callback();
                                }

                                R.SEND_HTTP(
                                    req,
                                    {
                                        url: CORE_APIConfig.coreAPI.sendCodeSms,
                                        method: 'POST',
                                        data  : {
                                            phone : item.o_phone,
                                            type  : 2,
                                            money : (item.o_money - nowStagePrice).toFixed(2)
                            }
                                    },
                                    function (err, data) {

                                        //发送短信
                                        
                                        //console.log("已给" + item.o_phone + "发送了退款短信");
                                        //console.log(data);

                                        callback();

                                    }
                                );

                                // //console.log(data);
                                // cb();
                            }
                        );
                    });
                });
                async.waterfall(tasks, cb);
            }
        },
        /**************************************************/
        function(cb){
            //创建添加任务
            var tasks = [];

            if (shouldRefundOrderInfo.length <= 0) {

                cb();

            } else {
                //循环节点列表
                shouldRefundOrderInfo.forEach(function (item, i) {
                    //创建每一个插入任务
                    tasks.push(function (callback) {


                        console.log("准备更新订单支付金额：" + nowStagePrice);
                      

                        //更新订单价格
                        R.SEND_HTTP(
                            req,
                            {
                                url: CORE_APIConfig.coreAPI.update_order,
                                method: 'POST',
                                data: {
                                    o_no: item.o_no,
                                    o_money:nowStagePrice,
                                    o_pay_money:nowStagePrice

                                }

                            },
                            function (err, data) {

                                //console.log(66666666,data);
                                callback();
                            }
                        );
                    });
                });
                async.waterfall(tasks, cb);
            }
        },
        // /**************************************************/
            //查询用户信息
            function (cb) {

                R.SEND_HTTP(
                    req,
                    {
                        url: CORE_APIConfig.coreAPI.userSearch + "/u_id/" + bodyParams.u_id,
                        method: 'POST',
                        data: {
                            fields: ["u_nickname", "openid"].join(",")
                        }
                    },
                    function (err, data) {

                        //判断是否有错误信息
                        if (err) {
                            return cb(err, data);
                        }

                        userInfo = data.data[0];

                        cb();

                    }
                );

            },

            //给参与的用户发私信
            function (cb) {

                if (userInfo.openid == "" || userInfo.openid == null) {
                    return cb();
                }

                userInfo.openid = userInfo.openid.replace(/\*/g,"-"); 

                var clickurl = config.publicConfig.CLICK_SERVER + "collage_details?oa_id=" + bodyParams.oa_id;

                R.SEND_HTTP(
                    req,
                    {
                        url: "http://127.0.0.1:3400/weixin/templateMessagesSent",
                        method: 'POST',
                        data: {
                            openid: userInfo.openid,
                            type: "canTuanChengGong",
                            bookingName: oa_title,
                            bookingTime:common.timestampToTime(oa_start_time),
                            bookingMoney:nowStagePrice,
                            bookingValidity:common.timestampToTime(oa_end_time),
                            bookingLack : bodyParams.diff_count,
                            clickurl : clickurl
                        }
                    },
                    function (err, data) {
                        console.log(666,data);
                        //判断是否有错误信息
                        if (err) {
                            return cb(err, data);
                        }

                        //console.log("用户 ：" + userInfo.u_nickname + "发送成功");

                        cb();

                    }
                );


            },

            //判断团是否已达到上线（活动满员）
            function(cb){

                //活动已满员
                if(parseInt(joinCount) >= parseInt(userMaxCount)){

                    //console.log("活动满员");

                    cb();

                }else{

                    //console.log("活动未满员");

                   return RES.response(res, true);

                }


            },

            //查询参与的用户列表
            function(cb){

                R.SEND_HTTP(
                    req,
                    {
                        url: CORE_APIConfig.coreAPI.bulkPurchaseActivityJoinInfo + "/bpau_oaid/"+bodyParams.oa_id,
                        method: 'POST'
                    },
                    function (err, data) {
                        console.log(777,data);
                        //判断是否有错误信息
                        if (err) {
                            return cb(err, data);
                        }

                       

                        resultData.joinUserData = data.data;

                        //console.log("用户参与列表：" + resultData.joinUserData);

                        cb();

                    }
                );

            },

            //发送私信和短信
            function(cb){

                var tasks = [];

                //循环节点列表
                resultData.joinUserData.forEach(function (item, i) {

                   //创建每一个插入任务
                   tasks.push(function (callback) {

                    if(item.openid == "" || item.openid == null){
                        return callback();
                    }

                    var clickurl = config.publicConfig.CLICK_SERVER + "collage_details?oa_id=" + bodyParams.oa_id;


                    R.SEND_HTTP(
                        req,
                        {
                            url: "http://127.0.0.1:3400/weixin/templateMessagesSent",
                            method: 'POST',
                            data  : {
                                openid : item.openid,
                                type   : "pinTuanChengGong",
                                shopname : oa_title,
                                clickurl : clickurl
                            }
                        },
                        function (err, data) {

                            //发送短信
                            console.log("已给" + item.o_name + "发送了私信");
    
                            callback();

                        }
                    );

                   });


                });

                async.waterfall(tasks, cb);

            },

            function(cb){

                var tasks = [];

                //循环节点列表
                resultData.joinUserData.forEach(function (item, i) {

                    //创建每一个插入任务
                   tasks.push(function (callback) {

                        //发送短信
                        if( item.o_phone == "" ){
                            return callback();
                        }

                        R.SEND_HTTP(
                            req,
                            {
                                url: CORE_APIConfig.coreAPI.sendCodeSms,
                                method: 'POST',
                                data  : {
                                    phone : item.o_phone,
                                    type  : 3,
                                    activity_name : oa_title,
                                    order_no : item.o_no,
                                    consumer_code : item.cn_number,
                                    time  : oa_end_time
                                }
                            },
                            function (err, data) {

                                //发送短信
                                console.log("已给" + item.o_name + "发送了短信");

                                callback();

                            }
                        );

                   });

                });

                async.waterfall(tasks, cb);

            }

        ], function (err, result) {

            //返回最终拼接结果
            RES.response(res, true);

        }
    );

}